//
// Created by jingyuewu on 25-8-17.
//
#include <boost/asio.hpp>
#include <iostream>

std::string make_daytime_string() {
  using namespace std;
  time_t now = time(0);
  return ctime(&now);
}

int main(int argc, char **argv) {
  // if (argc != 2) {
  //   std::cerr << "Usage: " << argv[0] << " <port>" << std::endl;
  //   return 1;
  // }
  int port = 17239;
  try {
    boost::asio::io_context io_context;
    boost::asio::ip::tcp::acceptor acceptor(
        io_context,
        boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port));
    std::cout << "Server is listening on port " << port << std::endl;

    for (;;) {
      boost::asio::ip::tcp::socket socket(io_context);
      acceptor.accept(socket);

      // socket.write_some(boost::asio::buffer(make_daytime_string()));
      std::string msg = make_daytime_string();
      std::cout << "Server: " << msg << std::endl;

      boost::system::error_code error;
      boost::asio::write(socket, boost::asio::buffer(msg), error);

      socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
      socket.close();
      std::cout <<"Connection closed." << std::endl;
    }
    // socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both);
    // socket.close();
    // std::cout <<"Connection closed." << std::endl;
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
  }
  std::cout << "Server is stopped." << std::endl;
  return 0;
}